// 处理图片上传的接口 (一张图) 测试
const express = require('express')
//上传图片的包
const multer = require('multer')
const fs = require('fs')
const path = require('path')
const router = express.Router()
const config = require('../../config/baseinfo')
const HostUrl = `${config.PROTOCOL}://${config.HOST}:${config.PORT}`
// 引入jwt token工具
const JwtUtil = require('../../utils/jwt')
const { v4: uuidv4 } = require('uuid')
const db = require('../../config/db')

// 通过filename属性定制
let storage = multer.diskStorage({
    // 保存的路径
    destination: function (req, file, callback) {
        callback(null, 'public/upload/')
    },
    filename: function (req, file, callback) {
        // 将保存文件名设置为 字段名 + 时间戳，比如 logo-1478521468943
        let suffix = file.mimetype.split('/')[1]; //获取文件格式
        callback(null, file.fieldname + '-' + Date.now() + '.' + suffix);
    }
});
//生成的图片放入uploads文件夹下
let upload = multer({
    storage: storage
})

// 添加商品
router.post('/add_shop', function (req, res) {
    let name = req.body.name; // 商品名称
    let description = req.body.description; // 商品简介
    let img = req.body.img; //  图片 
    let price = req.body.price;   //商品价格


    let shop_insert_sql = '';

    shop_insert_sql = 'insert into shop(name,description,img,price) values("' + name + '","' + description + '","' + img + '","' + price + '")';


    db.query(shop_insert_sql, (err) => {
        if (err) {
            res.send({
                code: -1,
                msg: '添加失败',
                msg2: { name, description, img, price }
            })
        } else {
            res.send({
                code: 200,
                msg: '添加成功',
            });
        }
    })


})

// 删除商品
router.post('/del', function (req, res) {
    let cate_id = req.body.cate_id

    let sql = 'delete from shop where cate_id = "' + cate_id + '"';
    db.query(sql, function (err) {
        if (err) {
            res.send({
                code: -1,
                msg: '删除失败'
            })
        } else {
            res.send({
                code: 200,
                msg: '删除成功'
            })
        }
    })
})


// 商品列表
router.get('/list', function (req, res) {
    let cate_check_sql = 'select * from shop';
    db.query(cate_check_sql, (err, rows) => {
        if (err) {
            res.send({
                code: -1,
                msg: '获取商品列表失败'
            })
        } else {
            let row = rows
            for (i = 0; i < rows.length; i++) {
                row[i].img = `${HostUrl}/static/upload/${rows[i].img}`
            }
            res.send({
                code: 200,
                msg: '获取商品列表成功',
                result: row
            })
        }
    })
})
// 查询美食详情（id）
router.get('/detail', function (req, res) {
    // // 接收前端传递的用户ID
    let cate_id = req.query.cate_id;
    // let token = req.query.token;
    // // 请求需要进行token校验 
    // let jwt = new JwtUtil(token);
    // // 返回一个对象 
    // let result = jwt.verifyToken();
    // // 验通过执行下一步，否则就返回登陆信息不正确
    // if (result == 'err') {
    //     res.send({
    //         code: -1,
    //         msg: '登录已过期,请重新登录'
    //     });
    // } else {
    if (cate_id) {
        // 查询语句
        let sql = 'select * from cate where cate_id = "' + cate_id + '"';
        // console.log(sql)
        // 调用查询方法
        db.query(sql, function (err, rows) {
            if (err) {
                res.send({
                    code: -1,
                    msg: '查询失败'
                })
            } else {
                let row = rows
                row[0].img = `${HostUrl}/static/upload/${rows[0].img}`
                res.send({
                    code: 200,
                    result: row,
                    msg: '查询成功'
                });
            }
        });
    }
    // }
})



// 搜索商品
router.get('/search', function (req, res) {
    let keyword = req.query.keyword;
    // 多字段模糊查询
    let sql = "select * from shop where name LIKE CONCAT('%" + keyword + "%')";
    db.query(sql, (err, rows) => {
        if (err) {
            res.send({
                code: -1,
                msg: '查询失败',
                err
            })
        } else {
            if (rows.length == 0) {
                res.send({
                    code: 1,
                    msg: '没有该关键字匹配的内容'
                })
            } else {
                let row = rows
                for (i = 0; i < rows.length; i++) {
                    row[i].img = `${HostUrl}/static/upload/${rows[i].img}`
                }
                res.send({
                    code: 200,
                    msg: '查询成功',
                    result: rows
                })
            }
        }
    })

})

// 获取美食评论
router.get('/comment', function (req, res) {
    let cate_id = req.query.cate_id;
    // 多字段模糊查询
    let sql = "select * from comment where cate_id LIKE CONCAT('%" + cate_id + "%')";
    db.query(sql, (err, rows) => {
        if (err) {
            res.send({
                code: -1,
                msg: '查询失败',
                err
            })
        } else {
            if (rows.length == 0) {
                res.send({
                    code: 1,
                    msg: '没有评论'
                })
            } else {
                let row = rows
                for (i = 0; i < rows.length; i++) {
                    row[i].img = `${HostUrl}/static/upload/${rows[i].img}`
                }

                res.send({
                    code: 200,
                    msg: '查询成功',
                    result: rows
                })
            }
        }
    })
})

// 添加美食评论
// 
router.post('/publishs', function (req, res) {
    // 接收前端的标题
    let userName = req.body.userName || 5
    let img = req.body.img || 5
    let cate_id = req.body.cate_id || 5
    let topic_time = req.body.time || '2022-10-14'
    let content = req.body.content || "默认好评"
    let num = req.body.num || 5

    // res.send(id, cate_id,)
    if (cate_id) {
        // 处理提交的数据
        let cate_insert_sql = "insert into comment(userName,img,cate_id,content,topic_time,num) values('" + userName + "','" + img + "','" + cate_id + "','" + content + "','" + topic_time + "','" + num + "')"
        db.query(cate_insert_sql, function (err, rows) {
            if (err) {
                res.send({
                    code: -1,
                    msg: '评论失败',
                })
            } else {
                res.send({
                    code: 200,
                    msg: '评论成功',
                })
            }
        })
    }

})


module.exports = router;